from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.charts import Map
from fastapi import FastAPI
import uvicorn
from starlette.responses import HTMLResponse
from starlette.staticfiles import StaticFiles
from pyecharts.globals import CurrentConfig
from starlette.responses import RedirectResponse
from pyecharts.globals import ThemeType

import os
CurrentConfig.ONLINE_HOST = "/static/"
geo = Geo()
geo.add_schema(maptype="china")

citys = ["北京", "黄石", "南昌", "上海", "天津", "东莞"]

value = [1,2,3,4,5,6]
#value = ["","","","","",""]
##def map_base() -> Map:
##    c = (
##        Map()
##        .add("", [list(z) for z in zip(provinces, value)], "china")
##        .set_global_opts(title_opts=opts.TitleOpts(title="map-基本图形"))
##    )
##    return c
#加入数据
#print([list(z) for z in zip(citys, value)])
#geo.add('SN数量',[("广州", 100), ("乌鲁木齐", 66), ("济南", 500), ("武汉", 1000)])
#geo.render()
def geo(citys,values,title='title'):
    c = (
        Geo(init_opts=opts.InitOpts(theme=ThemeType.LIGHT,chart_id='geo1'))
        .add_schema(maptype="china",zoom=3.0,center=[120.97, 34.71])
        .add("geo", [list(z) for z in zip(citys, value)] )
        #.set_series_opts(label_opts=opts.LabelOpts(is_show=True,formatter="{b}:{@value}"))
        .set_series_opts(label_opts=opts.LabelOpts(font_size=18,is_show=True,formatter="{b}{@[2]}"))
        .set_global_opts(
            #visualmap_opts=opts.VisualMapOpts(),
            title_opts=opts.TitleOpts(title=title),
            legend_opts=opts.LegendOpts(is_show=False),
        )
    )

    web0=c.render_embed()
    #name0=web0.split('\n')[-5].split('.')[0]
    #name0='chart_geo1'
    #click0='.on("click", function(params) {        console.log(params);          window.open("/links/"+params.data.name);      });'
    click0='<script type="text/javascript"> chart_geo1.on("click", function(params) {        console.log(params);          window.open("/links/?q="+params.data.name);      });</script>'
    #print(name0+click0)

    #web1=web0.replace(end,'\n'+click0+end)
    web1=web0+click0
    return web1

app = FastAPI()
location='static'
app.mount('/static', StaticFiles(directory=location), name='static')
@app.get("/")
async def root(q: str=None):
    content=geo(citys,value,'SN每周数量')
    #print(content)

    return HTMLResponse(content=content+content)
@app.get("/links")
async def root(q: str=None):
    dict0={'天津':'https://www.baidu.com/s?wd=天津','北京':'https://www.baidu.com/s?wd=北京','南昌':'https://www.baidu.com/s?wd=南昌'}

    return RedirectResponse(url=dict0[q])
if __name__ == "__main__":
    os.system('"C:\Program Files\Google\Chrome\Application\chrome.exe" http://127.0.0.1:8080')
    uvicorn.run(app, host="0.0.0.0",port=8080,log_level="info")
